package com.zhaojonhy.zhaopangwb.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.zhaojonhy.zhaopangwb.R;
import com.zhaojonhy.zhaopangwb.adapter.EmotionPagerAdapter;
import com.zhaojonhy.zhaopangwb.adapter.EmotionGvAdapter;
import com.zhaojonhy.zhaopangwb.adapter.WriteStatusGridImgsAdapter;
import com.zhaojonhy.zhaopangwb.bean.Statuses;
import com.zhaojonhy.zhaopangwb.utils.AccessTokenKeeper;
import com.zhaojonhy.zhaopangwb.utils.Constants;
import com.zhaojonhy.zhaopangwb.utils.DisplayUtils;
import com.zhaojonhy.zhaopangwb.utils.EmojiUtils;
import com.zhaojonhy.zhaopangwb.utils.ImageUtils;
import com.zhaojonhy.zhaopangwb.utils.StringUtils;
import com.zhaojonhy.zhaopangwb.utils.TitleBuilder;
import com.zhaojonhy.zhaopangwb.utils.ToastUtils;
import com.zhaojonhy.zhaopangwb.widget.WrapHeightGridView;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2016/9/27.
 */

public class WriteStatusActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener{

    private ImageLoader imageLoader;

    //输入框
    private EditText et_write_status ;
    //添加九宫格的图片
    private WrapHeightGridView gv_write_status ;
    //转发微博的内容
    private View include_retweeted_status_card ;
    private ImageView iv_rstatus_image ;
    private TextView tv_rstatus_username ;
    private TextView tv_rstatus_content ;
    // 底部添加栏
    private ImageView iv_image;
    private ImageView iv_at;
    private ImageView iv_topic;
    private ImageView iv_emoji;
    private ImageView iv_add;
    // 表情选择面板
    private LinearLayout ll_emotion_dashboard;
    private ViewPager vp_emotion_dashboard;

    // 进度框
    private ProgressDialog progressDialog;

    private ArrayList<Uri> imageUris = new ArrayList<Uri>() ;
    private WriteStatusGridImgsAdapter statusImgsAdapter ;

    private EmotionPagerAdapter pagerAdapter ;

    private Statuses retweeted_status ;
    private Statuses cardStatus ; //实际需要显示的微博信息,原创
    private StatusesAPI statusesAPI ;
    private Oauth2AccessToken mAccessToken;

    //Uri转Bitmap
    private Bitmap bitmap ;
    private byte[] mBytes;

    //是否由转发接口传出数据
    private boolean isRetweet = false ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_status);

        imageLoader = ImageLoader.getInstance();
        retweeted_status = (Statuses) getIntent().getSerializableExtra("status");
        isRetweet = getIntent().getBooleanExtra("isRetweet",false) ;

        Log.d("isRetweet-->","boolean:" +isRetweet) ;

        initView() ;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titleBarTvLeft :
                WriteStatusActivity.this.finish();
                break;
            case R.id.titleBarTvRight :
                sendStatus() ;
                //微博发送成功后，设置Result结果数据，然后关闭本页面
                Intent data = new Intent() ;
                data.putExtra("sendSatusSuccess",true) ;
                setResult(RESULT_OK,data);
                break;
            //底部点击图片按钮，弹出一个图片选择对话框
            case R.id.iv_image :
                ImageUtils.showImagePickDialog(this) ;
                break;
            case R.id.iv_at :
                break;
            case R.id.iv_topic :
                break;
            case R.id.iv_emoji :
                //按下表情面板对应的是面板的显示
                //判断面板的当前状态，如果面板是隐藏点击下是显示，显示状态下按下表情按钮是隐藏
                if( ll_emotion_dashboard.getVisibility() == View.VISIBLE){
                    ll_emotion_dashboard.setVisibility(View.GONE) ;
                    //这时候表情按钮是表情的
                    iv_emoji.setImageResource(R.drawable.btn_insert_emotion);
                }else {
                    ll_emotion_dashboard.setVisibility(View.VISIBLE) ;
                    //这时候表情按钮是键盘的
                    iv_emoji.setImageResource(R.drawable.btn_insert_keyboard);
                }
                break;
            case R.id.iv_add :
                break;
            default:
                break;

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //末尾的点击事件
        Object itemAdapter = parent.getAdapter() ;
        //类型的判断，及是WriteStatusGridImgsAdapter 的adpter
        if( itemAdapter instanceof WriteStatusGridImgsAdapter ){
            if( position == statusImgsAdapter.getCount() - 1 ){
                ImageUtils.showImagePickDialog(this) ;
            }
        }else if( itemAdapter instanceof EmotionGvAdapter ){
            EmotionGvAdapter emotionGvAdapter = (EmotionGvAdapter) itemAdapter ;

            //最后一个回退键
            if (position == emotionGvAdapter.getCount() - 1) {
                //利用系统的回退键进行相应的处理
                //对应系统键盘的动作操作，这里对应删除的操作，对应新建KeyEvent里面的按下操作
                et_write_status.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DEL)) ;

            }else{
                String emotionName = emotionGvAdapter.getItem(position) ;
                //获取光标的位置，EdiText有提供一个叫做getSelectionStart()的方法
                int curPosition = et_write_status.getSelectionStart() ;
                //拼装字符串使用，StringBuilder,在()后面的内容操作
                StringBuilder sb = new StringBuilder(et_write_status.getText().toString()) ;
                sb.insert(curPosition,emotionName) ;//有sb.Append ,sb.Remove, sb.Replace等操作
                //利用先前的StringUtils类进行表情的显示
                SpannableString weiboContent = StringUtils.getWeiboContent(this,et_write_status,sb.toString()) ;
                et_write_status.setText(weiboContent) ;
                //把光标移动在表情字符串的后面
                et_write_status.setSelection(curPosition + emotionName.length());
            }
        }

    }

    private void initView() {

        new TitleBuilder(this)
                .setTitleText("发微博")
                .setRightText("发送")
                .setRightOnClickListener(this)
                .setLeftText("取消")
                .setLeftOnClickListener(this)
                .build();

        //输入框
        et_write_status = (EditText) findViewById(R.id.et_write_status) ;
        //添加九宫格的图片
        gv_write_status = (WrapHeightGridView) findViewById(R.id.gv_write_status) ;
        //转发微博的内容
        include_retweeted_status_card = findViewById(R.id.include_retweeted_status_card) ;
        iv_rstatus_image = (ImageView)include_retweeted_status_card.findViewById(R.id.iv_rstatus_image) ;
        tv_rstatus_username = (TextView)include_retweeted_status_card.findViewById(R.id.tv_rstatus_username) ;
        tv_rstatus_content = (TextView)include_retweeted_status_card.findViewById(R.id.tv_rstatus_content) ;
        //底部添加栏
        iv_image = (ImageView) findViewById(R.id.iv_image) ;
        iv_at = (ImageView) findViewById(R.id.iv_at) ;
        iv_topic = (ImageView) findViewById(R.id.iv_topic) ;
        iv_emoji = (ImageView) findViewById(R.id.iv_emoji) ;
        iv_add = (ImageView) findViewById(R.id.iv_add) ;
        // 表情选择面板
        ll_emotion_dashboard = (LinearLayout) findViewById(R.id.ll_emotion_dashboard);
        vp_emotion_dashboard = (ViewPager) findViewById(R.id.vp_emotion_dashboard);

        // 进度框
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("微博发布中...");

        statusImgsAdapter = new WriteStatusGridImgsAdapter(this,imageUris,gv_write_status) ;
        gv_write_status.setAdapter(statusImgsAdapter) ;
        gv_write_status.setOnItemClickListener(this);

        //底部点击
        iv_image.setOnClickListener(this);
        iv_at.setOnClickListener(this);
        iv_topic.setOnClickListener(this);
        iv_emoji.setOnClickListener(this);
        iv_add.setOnClickListener(this);

        //初始化引用微博方法
        initRetweetedStatus() ;
        initEmotion() ;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ContentResolver resolver = getContentResolver();
        switch (requestCode){
            case ImageUtils.RQUEST_CODE_FROM_CAMERA :
                // 如果拍照取消,将之前新增的图片地址删除
                if ( resultCode == RESULT_CANCELED  ) {
                    ImageUtils.deletImageUri(this,ImageUtils.imageUriFromCamera) ;
                }else {
                    //不能用data.getData() ,这样获取的是一个压缩图
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera ;
                    imageUris.add(imageUriCamera) ;
                    updateimage() ;

                    try {
                        Bundle extras = data.getExtras();
                        bitmap = (Bitmap) extras.get("data");
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        mBytes = baos.toByteArray();

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case ImageUtils.RQUEST_CODE_FROM_ALBUM :
                if ( resultCode == RESULT_CANCELED  ) {
                    return;
                }
                Uri imageUri = data.getData() ;
                imageUris.add(imageUri) ;
                updateimage() ;

                try {
                    mBytes = readStream(resolver.openInputStream(Uri.parse(imageUri.toString())));
                    // 将字节数组转换为ImageView可调用的Bitmap对象
                    bitmap = getPicFromBytes(mBytes, null);
                    // 把得到的图片绑定在控件上显示
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }

                break;
        }
    }

    /**
     * 更新图片显示
     */
    private void updateimage() {
        //如果数据是空的就隐藏gridView
        if(imageUris.size() > 0 ){
            gv_write_status.setVisibility(View.VISIBLE);
            statusImgsAdapter.notifyDataSetChanged() ;
        }else {
            gv_write_status.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化引用微博内容
     */
    private void initRetweetedStatus() {

        if( retweeted_status != null ){
            Statuses rrStatus = retweeted_status.getRetweeted_status() ;
            if( rrStatus != null ){
                String content = "//@"+ retweeted_status.getUser().getName() +
                        ":" + retweeted_status.getText() ;
                et_write_status.setText(content);
                String retImgUrl = rrStatus.getUser().getProfile_image_url() ;
                if(TextUtils.isEmpty(retImgUrl)){
                    iv_rstatus_image.setVisibility(View.GONE);
                }else {
                    iv_rstatus_image.setVisibility(View.VISIBLE);
                    imageLoader.displayImage(retImgUrl,iv_rstatus_image);
                }
                tv_rstatus_username.setText("@" + rrStatus.getUser().getName() );
                tv_rstatus_content.setText(rrStatus.getText());

            }else { //原创微博
                et_write_status.setText("转发微博");
                cardStatus = retweeted_status ;
                String imgUrl = cardStatus.getUser().getProfile_image_url() ;
                if(TextUtils.isEmpty(imgUrl)){
                    iv_rstatus_image.setVisibility(View.GONE);
                }else {
                    iv_rstatus_image.setVisibility(View.VISIBLE);
                    imageLoader.displayImage(imgUrl,iv_rstatus_image);
                }
                tv_rstatus_username.setText("@" + cardStatus.getUser().getName() );
                tv_rstatus_content.setText(cardStatus.getText());
            }

            iv_image.setVisibility(View.GONE); //转发微博底部不能有图片
            include_retweeted_status_card.setVisibility(View.VISIBLE);
        }else {
            include_retweeted_status_card.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化表情面板内容
     *
     */

    private void initEmotion() {
        //前20个是表情图标，最后一个是回退按钮，做3行7列，每一列的宽度是多大
        //需要屏幕宽度去计算,动态获取屏幕宽度
        int screenWidth = DisplayUtils.getScreenWidthPixels(this) ;
        //设置一个间隔为dp8的间距并转为像素
        int spacing = DisplayUtils.dp2px( this , 8 ) ;
        int itemWidth = ( screenWidth - spacing * 8 ) / 7 ;
        int gvHeight = itemWidth * 3 + spacing * 4 ;

        //遍历全部表情，每20个一组在退回键创建一个gridView
        //获取表情名字，对应的是键
        List<String> emojiNames = new ArrayList<String>() ;
        List<GridView> gridViews = new ArrayList<GridView>() ;
        for( String emojiName : EmojiUtils.emojiMap.keySet() ){
            emojiNames.add(emojiName) ; //加入到名字集合中

            //每为20个一组创建一个gridView
            if( emojiNames.size() == 20 ) {
                GridView gv = createEmotionGridView(emojiNames ,screenWidth ,spacing ,itemWidth ,gvHeight) ;
                gridViews.add(gv) ;

                //每满20 emojiNames
                emojiNames = new ArrayList<String>() ; //会剩余没有满20 的外部处理
            }
        }
        if( emojiNames.size() > 0 ) {
            GridView gv = createEmotionGridView(emojiNames ,screenWidth ,spacing ,itemWidth ,gvHeight) ;
            gridViews.add(gv) ;
        }

        pagerAdapter = new EmotionPagerAdapter(gridViews) ;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( screenWidth ,gvHeight ) ;
        vp_emotion_dashboard.setLayoutParams(params);
        vp_emotion_dashboard.setAdapter(pagerAdapter);
    }
    /**
     * 创建显示表情的GridView
     */

    public GridView createEmotionGridView(List<String> emojiNames ,int gvWidth ,
                                          int spacing ,int itemWidth ,int gvHeight) {
        GridView gv = new GridView(this) ;
        gv.setBackgroundResource(R.color.white);
        gv.setPadding(spacing, spacing, spacing, spacing);
        gv.setSelector(R.color.transparent);
        gv.setNumColumns(7);
        gv.setHorizontalSpacing(spacing);
        gv.setVerticalSpacing(spacing);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(gvWidth,gvHeight) ;
        gv.setLayoutParams(layoutParams);

        //每20+1个退格键做一个gridview adapter
        EmotionGvAdapter gvAdapter = new EmotionGvAdapter(this ,emojiNames ,itemWidth ) ;
        gv.setAdapter(gvAdapter);
        gv.setOnItemClickListener(this);
        return gv ;
    }

    /**
     * 发送微博
     */
    private void sendStatus() {
        String statusContent = et_write_status.getText().toString() ;
        if(TextUtils.isEmpty(statusContent)) {
            ToastUtils.showToast(this,"微博内容不能为空", Toast.LENGTH_LONG);
            return;
        }
        String imgFilePath = null ;
        if( imageUris.size() > 0 ) {
            Uri uri = imageUris.get(0) ; //api有限制只能发送单图
            imgFilePath = ImageUtils.getImageAbsolutePath(this,uri) ;
        }
        long retweetedStatusId  = cardStatus == null ? retweeted_status.getRetweeted_status().getId()
                : cardStatus.getId() ;
        mAccessToken = AccessTokenKeeper.readAccessToken(this);
        statusesAPI = new StatusesAPI(this, Constants.APP_KEY, mAccessToken) ;
        if(isRetweet) {
            statusesAPI.repost(retweetedStatusId, statusContent, 0, new RequestListener() {
                @Override
                public void onComplete(String s) {
                    ToastUtils.showToast(WriteStatusActivity.this,"发送成功",Toast.LENGTH_LONG);
                    WriteStatusActivity.this.finish();
                }

                @Override
                public void onWeiboException(WeiboException e) {
                    ToastUtils.showToast(WriteStatusActivity.this,"发送失败",Toast.LENGTH_LONG);
                    e.printStackTrace();
                }
            });
        }else{
            if( bitmap == null ){
                statusesAPI.update(statusContent, "0.0", "0.0",
                        new RequestListener() {
                            @Override
                            public void onComplete(String s) {
                                ToastUtils.showToast(WriteStatusActivity.this,"发送成功",Toast.LENGTH_LONG);
                                WriteStatusActivity.this.finish();
                            }

                            @Override
                            public void onWeiboException(WeiboException e) {
                                ToastUtils.showToast(WriteStatusActivity.this,"发送失败",Toast.LENGTH_LONG);
                                e.printStackTrace();
                            }
                        });
            }else {
                ToastUtils.showToast(WriteStatusActivity.this,"bitmap != null",Toast.LENGTH_LONG);
                statusesAPI.upload(statusContent,bitmap, "0.0", "0.0",
                        new RequestListener() {
                            @Override
                            public void onComplete(String s) {
                                ToastUtils.showToast(WriteStatusActivity.this,"发送成功",Toast.LENGTH_LONG);
                                WriteStatusActivity.this.finish();
                            }

                            @Override
                            public void onWeiboException(WeiboException e) {
                                ToastUtils.showToast(WriteStatusActivity.this,"发送失败",Toast.LENGTH_LONG);
                                e.printStackTrace();
                            }
                        });
            }
        }
    }

//bitmap处理方法
    public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null)
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
            else
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return null;
    }


    public static byte[] readStream(InputStream inStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;


    }
}
